package com.youxin.cpcenter.service.impl;

import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.classify.RequestClassifyIndustryBean;
import com.youxin.busfoundation.bean.classify.ResponseClassifyBean;
import com.youxin.busfoundation.bean.ent.QueryEntMemberBean;
import com.youxin.busfoundation.bean.ent.RequestCompanyInfoBean;
import com.youxin.busfoundation.bean.ent.RequestEntInfo;
import com.youxin.busfoundation.bean.leads.RequestPoolBean;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.BusinessException;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.UidGenerator;
import com.youxin.busfoundation.common.es.SearchCompanyInfo;
import com.youxin.busfoundation.common.es.bean.*;
import com.youxin.busfoundation.common.name.NameOperator;
import com.youxin.cpcenter.bean.*;
import com.youxin.cpcenter.dao.TbCompanyInfoMapper;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.model.TbCompanyInfo;
import com.youxin.cpcenter.model.TbEntCluePoolCompany;
import com.youxin.cpcenter.service.*;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.DateUtil;
import com.youxin.foundation.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: CompanyInfoServiceImpl
 * @Description: 企业业务
 * @author Kris.wang
 * @date 2017年11月30日 下午14:01:02
 */
@Service("companyInfoService")
public class CompanyInfoServiceImpl extends BaseServiceImpl implements CompanyInfoService {

	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;

	@Autowired
	private CluePoolCompanyService cluePoolCompanyService;

	@Autowired
	private ClassifyServiceImpl classifyService;

	@Autowired
	public SearchService searchService;

	@Autowired
	public SearchCompanyService searchCompanyService;

	@Autowired
	public ViewLeadsService viewLeadsService;

	@Autowired
	private TbCompanyInfoMapper tbCompanyInfoMapper;

	@Autowired
	private EntMemberIdentifyService entMemberIdentifyService;

	/**
	 * @desc 下载ES数据到业务数据库
	 * @param bean
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public TbCompanyInfo copyEsToCompany(RequestCompanyBean bean) throws Exception {
		// ES企业数据已存在，则直接退出
		TbCompanyInfo tbCompanyInfo = null;
		tbCompanyInfo = tbCompanyInfoMapper.selectByUid(bean.getCompanyUid());
		if (tbCompanyInfo != null) {
			return tbCompanyInfo;
		}

		// 获取ES数据
		CompanyBaseBean companyBaseBean = null;
		RequestCompanyInfoBean requestCompanyInfoBean = new RequestCompanyInfoBean();
		requestCompanyInfoBean.setUid(bean.getCompanyUid());
		companyBaseBean = new SearchCompanyInfo().queryCompanyInfo(requestCompanyInfoBean, new String[] {});

		// 导入数据库
		tbCompanyInfo = new TbCompanyInfo();
		tbCompanyInfo.setId(KeyGenerationUtils.generateKey());
		tbCompanyInfo.setUid(UidGenerator.getUid(companyBaseBean.getFullName()));
		tbCompanyInfo.setFullName(companyBaseBean.getFullName());
		tbCompanyInfo.setShortName(companyBaseBean.getShortName());
		tbCompanyInfo.setAliasName(companyBaseBean.getAliasName());
		tbCompanyInfo.setCreditCode(companyBaseBean.getCreditCode());
		tbCompanyInfo.setRegisterId(companyBaseBean.getRegNumber());
		tbCompanyInfo.setOrganizationTypeStr(companyBaseBean.getCompanyOrgType());
		tbCompanyInfo.setOrganizationCode(companyBaseBean.getOrgNumber());
		tbCompanyInfo.setTaxpayerIdentity(companyBaseBean.getTaxNumberNo());
		tbCompanyInfo.setRegisterOffice(companyBaseBean.getRegLocation());
		tbCompanyInfo.setProvince(companyBaseBean.getProvince());
		tbCompanyInfo.setCity(companyBaseBean.getCity());
		tbCompanyInfo.setCorporateName(companyBaseBean.getLegalPersonName());
		tbCompanyInfo.setDistrict(0);
		tbCompanyInfo.setRegCapital(companyBaseBean.getRegCapital());
		tbCompanyInfo.setRegCapitalUnit(companyBaseBean.getRegUnit());
		tbCompanyInfo.setEstiblishTime(companyBaseBean.getRegTime());
		tbCompanyInfo.setRegisterOffice(companyBaseBean.getRegLocation());
		tbCompanyInfo.setMainSalesArea("");
		tbCompanyInfo.setLogoPath(companyBaseBean.getLogoUrl());
		tbCompanyInfo.setRegStatus(companyBaseBean.getRegStatus());
		tbCompanyInfo.setScale(Short.valueOf(companyBaseBean.getScale()));
		tbCompanyInfo.setIndustrySmall(companyBaseBean.getIndustrySmallStr());
		tbCompanyInfo.setIndustry(companyBaseBean.getIndustryStr());
		tbCompanyInfo.setIntroduction(companyBaseBean.getIntroduction());
		tbCompanyInfo.setBusinessScope(companyBaseBean.getBusinessScope());
		tbCompanyInfo.setLocationShort(companyBaseBean.getLocation());
		tbCompanyInfo.setRegLocation(companyBaseBean.getRegLocation());
		tbCompanyInfo.setLocation(companyBaseBean.getLocation());
		tbCompanyInfo.setDataSource("ES");
		tbCompanyInfo.setProductIntro("");
		tbCompanyInfo.setProductAdvantage("");
		tbCompanyInfo.setProductPrice("");
		tbCompanyInfo.setCompanyCase("");
		tbCompanyInfo.setOperatingPeriod("");
		tbCompanyInfo.setCompanyPhone(companyBaseBean.getPhone());
		tbCompanyInfo.setCompanyEmail(companyBaseBean.getEmail());
		tbCompanyInfo.setCompanyFax("");
		tbCompanyInfo.setCompanyPost("");
		tbCompanyInfo.setLocationCode("");
		tbCompanyInfo.setWebsite(companyBaseBean.getWebSite());
		tbCompanyInfo.setCompanyType(new Short("0"));
		tbCompanyInfo.setRegisterType(new Short("0"));
		tbCompanyInfo.setAddTime(DateUtil.getDateForInt());
		tbCompanyInfo.setCorporateName("");
		tbCompanyInfo.setIsDelete(Short.valueOf("0"));
		tbCompanyInfo.setFromTime(companyBaseBean.getFromTime());
		tbCompanyInfo.setToTime(companyBaseBean.getToTime());
		String approvedTime = companyBaseBean.getApprovedTime() + "";
		approvedTime = approvedTime.substring(0, approvedTime.length() - 3);
		tbCompanyInfo.setApprovedTime(Integer.parseInt(approvedTime));
		tbCompanyInfo.setRegLocation(companyBaseBean.getRegLocation());
		tbCompanyInfo.setIsDownTyc(new Short("0"));
		tbCompanyInfo.setArea("");
		tbCompanyInfo.setUpdateTime(0);
		tbCompanyInfo.setMobile("");
		int ret = tbCompanyInfoMapper.insertBaseInfo(tbCompanyInfo);
		if (ret == 0) {
			throw new BusinessException("下载ES数据到业务数据库失败");
		}

		return tbCompanyInfo;
	}

	/**
	 * @desc 企业画像-基本信息
	 * @param bean
	 * @return
	 */
	@Override
	public ResponseObject companyInfo(RequestCompanyInfoBean bean) {
		// 用户信息
		UserInfo userInfo = LoginAuth.getUserInfo();

		// 判断当前用户是否收藏线索
		RequestPoolBean requestPoolBean = new RequestPoolBean();
		requestPoolBean.setCollectCompanyUid(bean.getUid());
		requestPoolBean.setCompanyUid(userInfo.getCompanyUid());
		int hasCuePool = cluePoolCompanyService.verify(requestPoolBean);
		// 已收藏时，获取最新一条记录
		TbEntCluePoolCompany tbEntCluePoolCompany = cluePoolCompanyService.selectLatestRecord(requestPoolBean);

		// ES企业信息
		CompanyBaseBean companyBaseBean = null;
		try {
			RequestCompanyInfoBean requestBean = new RequestCompanyInfoBean();
			requestBean.setUid(bean.getUid());
			String[] attr = { "full_name", "address", "industry", "introduction", "website", "phone", "address",
					"short_name", "logo_url", "business_scope" };
			companyBaseBean = searchCompanyService.queryCompanyInfo(requestBean, attr);
		} catch (Exception e) {
			companyBaseBean = new CompanyBaseBean();
		}

		// 映射行业
		List<String> industryName = new ArrayList<String>();
		if (companyBaseBean.getIndustry() != null) {
			RequestClassifyIndustryBean RequestClassifyIndustryBean = new RequestClassifyIndustryBean();
			RequestClassifyIndustryBean.setUids(companyBaseBean.getIndustry());
			List<ResponseClassifyBean> totallists = classifyService.selectByUids(RequestClassifyIndustryBean);
			for (ResponseClassifyBean item : totallists) {
				industryName.add(item.getName());
			}
		}

		CompanyBean companyBean = new CompanyBean();
		companyBean.setUid(companyBaseBean.getUid());
		companyBean.setFullName(companyBaseBean.getFullName());
		companyBean.setAddress(companyBaseBean.getLocation());
		companyBean.setShortName(companyBaseBean.getShortName());
		companyBean.setLogoUrl(companyBaseBean.getLogoUrl());
		companyBean.setIntroduction(companyBaseBean.getIntroduction());
		companyBean.setBusinessScope(companyBaseBean.getBusinessScope());
		companyBean.setIndustry(companyBaseBean.getIndustry());
		companyBean.setIndustryName(industryName);
		companyBean.setLocation(companyBaseBean.getAddress());
		companyBean.setPhone(companyBaseBean.getPhone());
		companyBean.setWebsite(companyBaseBean.getWebSite());
		companyBean.setPhone(companyBaseBean.getPhone());
		companyBean.setHasCuePool(hasCuePool);
		companyBean.setIdentity(entMemberIdentifyService.verifyCompanyCert(bean.getUid()));
		companyBean.setStatus(new Short("0"));
		companyBean.setMemberName("");

		// 有收藏记录
		if (tbEntCluePoolCompany != null) {
			companyBean.setStatus(tbEntCluePoolCompany.getStatus());
			companyBean.setMemberName(tbEntCluePoolCompany.getMemberName());
		}

		// 游览记录
		viewLeadsService.updateViewLeads(bean.getUid(), userInfo);

		return ResponseObject.successObject(companyBean);
	}

	/**
	 * @desc 企业商务合作
	 * @param requestBean
	 * @return
	 * @throws Exception
	 */
	@Override
	public ResponseObject searchCooperate(RequestCooperateBean requestBean) {
		// 联系人
		List<PortraitContactBean> contactBeansList = null;
		try {
			RequestContactBean requestContactBean = new RequestContactBean();
			requestContactBean.setCompanyUid(requestBean.getCompanyUid());
			contactBeansList = searchCompanyService.searchPortraitContact(requestContactBean);
			if (!ArrayUtils.isEmpty(contactBeansList)) {
				/**
				 * 脱敏
				 */
				List<String> mobiles = contactBeansList.stream()
						.filter((t) -> !StringUtils.isNullOrEmpty(t.getMobile())).map((t) -> {
							return t.getMobile();
						}).collect(Collectors.toList());
				QueryEntMemberBean queryEntMemberBean = new QueryEntMemberBean();
				queryEntMemberBean.setCompanyUid(requestBean.getCompanyUid());
				queryEntMemberBean.setMobiles(mobiles);
				List<String> queryResults = tbEntMemberInfoMapper.selectByCompanyUidAndMobiles(queryEntMemberBean);
				for (PortraitContactBean item : contactBeansList) {
					if (!queryResults.contains(item.getMobile())) {
						item.setName(NameOperator.hideName(item.getName()));
						item.setTitle(NameOperator.hidePosition(item.getTitle()));
						item.setPosition(NameOperator.hidePosition(item.getTitle()));
					}
				}
			}
		} catch (Exception e) {
			// logger.error("searchCooperate1", e);
			contactBeansList = new ArrayList<>();
		}

		// 资源
		List<PortraitResourceBean> resourceBeansList = null;
		try {
			RequestResourceBean requestResourceBean = new RequestResourceBean();
			requestResourceBean.setCompanyUid(requestBean.getCompanyUid());
			resourceBeansList = searchCompanyService.searchPortraitResource(requestResourceBean);
		} catch (Exception e) {
			// logger.error("searchCooperate2", e);
			resourceBeansList = new ArrayList<>();
		}

		// 产品和服务
		List<PortraitProductServiceBean> productServiceBeansList = null;
		try {
			RequestProductServiceBean requestProductServiceBean = new RequestProductServiceBean();
			requestProductServiceBean.setCompanyUid(requestBean.getCompanyUid());
			productServiceBeansList = searchCompanyService.searchPortraitProductService(requestProductServiceBean);
		} catch (Exception e) {
			// logger.error("searchCooperate3", e);
			productServiceBeansList = new ArrayList<>();
		}

		// 商务合作
		CompanyCooperateBean companyCooperateBean = new CompanyCooperateBean();
		companyCooperateBean.setContactNumber(contactBeansList.size());
		companyCooperateBean.setResourceNumber(resourceBeansList.size());
		companyCooperateBean.setProductServiceNumber(productServiceBeansList.size());
		companyCooperateBean.setContactInfo(contactBeansList);
		companyCooperateBean.setResourceInfo(resourceBeansList);
		companyCooperateBean.setProductServiceInfo(productServiceBeansList);
		return ResponseObject.successObject(companyCooperateBean);
	}

	/**
	 * @desc 企业画像-风险预警
	 * @param bean
	 * @return
	 */
	@Override
	public ResponseObject companyRiskwarn(RequestRiskwarnBean bean) {
		// ES企业数据
		CompanyBaseBean companyBaseBean = null;
		try {
			RequestCompanyInfoBean requestBean = new RequestCompanyInfoBean();
			requestBean.setUid(bean.getCompanyUid());
			String[] attr = { "announcement", "operation", "lawsuit" };
			companyBaseBean = searchCompanyService.queryCompanyInfo(requestBean, attr);
		} catch (Exception e) {
			companyBaseBean = new CompanyBaseBean();
		}

		Integer announcementNumber = 0;
		Integer operationNumber = 0;
		Integer lawSuitNumber = 0;
		if (companyBaseBean.getAnnouncement() != null) {
			announcementNumber = companyBaseBean.getAnnouncement().size();
		}
		if (companyBaseBean.getOperation() != null) {
			operationNumber = companyBaseBean.getOperation().size();
		}

		List<LawsuitBean> lawsuitList = new ArrayList<>();
		if (companyBaseBean.getLawsuit() != null) {
			lawSuitNumber = companyBaseBean.getLawsuit().size();
			// 风险预警时间格式化
			lawsuitList = companyBaseBean.getLawsuit();
			for (LawsuitBean item:lawsuitList) {
				item.setDate(_formatDate(item.getDate()));
			}
		}

		CompanyRiskwarnBean companyRiskwarnBean = new CompanyRiskwarnBean();
		companyRiskwarnBean.setOperation(companyBaseBean.getOperation());
		companyRiskwarnBean.setOperationNumber(operationNumber);
		companyRiskwarnBean.setAnnouncementNumber(announcementNumber);
		companyRiskwarnBean.setAnnouncement(companyBaseBean.getAnnouncement());
		companyRiskwarnBean.setLawSuit(lawsuitList);
		companyRiskwarnBean.setLawSuitNumber(lawSuitNumber);
		return ResponseObject.successObject(companyRiskwarnBean);
	}

	/**
	 * @desc 企业画像-企业实力
	 * @param bean
	 * @return
	 */
	@Override
	public ResponseObject companyStrength(RequestStrengthBean bean) {
		// ES企业数据
		CompanyBaseBean companyBaseBean = null;
		try {
			RequestCompanyInfoBean requestBean = new RequestCompanyInfoBean();
			requestBean.setUid(bean.getCompanyUid());
			String[] attr = { "finance", "invest", "tax_info", "members", "legal_person_name", "reg_number",
					"org_number", "tax_number", "company_org_type", "credit_code", "tax_number_no", "reg_status",
					"company_type", "approved_time", "org_approved_institution", "reg_time", "annual_sales",
					"reg_capital", "reg_unit", "index_baidu", "index_wechat", "patent", "copyright", "partners",
					"business_scope" };
			companyBaseBean = searchCompanyService.queryCompanyInfo(requestBean, attr);
		} catch (Exception e) {
			companyBaseBean = new CompanyBaseBean();
		}

		// 客户案例
		List<PortraitCustomerCaseBean> customerCaseBeanList = new ArrayList<PortraitCustomerCaseBean>();
		if (companyBaseBean.getPartners() != null) {
			List<String> Partners = Arrays.asList(companyBaseBean.getPartners().split(",", -1));
			try {
				List<CompanyBaseBean> list = searchCompanyService.queryCompanyInfos(Partners);
				for (CompanyBaseBean item : list) {
					PortraitCustomerCaseBean portraitCustomerCaseBean = new PortraitCustomerCaseBean();
					portraitCustomerCaseBean.setBrandName(item.getFullName());
					portraitCustomerCaseBean.setCompanyUid(item.getUid());
					portraitCustomerCaseBean.setLogoUrl(item.getLogoUrl());
					customerCaseBeanList.add(portraitCustomerCaseBean);
				}
			} catch (Exception e) {
				List<CompanyBaseBean> list = new ArrayList<CompanyBaseBean>() {
				};
			}
		}

		Integer financeNumber = companyBaseBean.getFinance() != null ? companyBaseBean.getFinance().size() : 0;
		Integer investNumber = companyBaseBean.getInvest() != null ? companyBaseBean.getInvest().size() : 0;
		Integer taxNumber = companyBaseBean.getTax() != null ? companyBaseBean.getTax().size() : 0;
		Integer patentNumber = companyBaseBean.getPatent() != null ? companyBaseBean.getPatent().size() : 0;
		Integer copyrightNumber = companyBaseBean.getCopyright() != null ? companyBaseBean.getCopyright().size() : 0;

		// 融资相关信息
		String financeAmount = "0";
		String financeRound = "未明确";
		List<FinanceBean> financeList = companyBaseBean.getFinance();
		if (financeNumber > 0) {
			int i = 0;
			String lastDate = "";
			for (FinanceBean item : financeList) {
				if (i == 0) {
					financeAmount = item.getMoney();
					financeRound = item.getRound();
					lastDate = item.getDate();
				} else {
					if (this._compareDate(item.getDate(), lastDate) == true) {
						financeAmount = item.getMoney();
						financeRound = item.getRound();
						lastDate = item.getDate();
					}
				}
				item.setDate(DateUtil.msecondTimeToString(Long.valueOf(item.getDate()), "yyyy-MM-dd"));
				i++;
			}
		}

		// 企业实力
		CompanyStrengthBean companyStrengthBean = new CompanyStrengthBean();
		companyStrengthBean.setCustomerCase(customerCaseBeanList);
		companyStrengthBean.setTeamStrength(companyBaseBean.getMembers());
		companyStrengthBean.setFinance(financeList);
		companyStrengthBean.setFinanceNumber(financeNumber);
		companyStrengthBean.setInvest(companyBaseBean.getInvest());
		companyStrengthBean.setInvestNumber(investNumber);
		companyStrengthBean.setTax(companyBaseBean.getTax());
		companyStrengthBean.setTaxNumber(taxNumber);
		companyStrengthBean.setPatent(companyBaseBean.getPatent());
		companyStrengthBean.setPatentNumber(patentNumber);
		companyStrengthBean.setCopyright(companyBaseBean.getCopyright());
		companyStrengthBean.setCopyrightNumber(copyrightNumber);
		companyStrengthBean.setLegalPersonName(companyBaseBean.getLegalPersonName());
		companyStrengthBean.setRegNumber(companyBaseBean.getRegNumber());
		companyStrengthBean.setOrgNumber(companyBaseBean.getOrgNumber());
		companyStrengthBean.setCreditCode(companyBaseBean.getCreditCode());
		companyStrengthBean.setTaxNumberNo(companyBaseBean.getTaxNumberNo());
		companyStrengthBean.setRegStatus(companyBaseBean.getRegStatus());
		companyStrengthBean.setApprovedTime(this._formatDate(companyBaseBean.getApprovedTime()));
		companyStrengthBean.setCompanyType(companyBaseBean.getCompanyOrgType());
		companyStrengthBean.setCompanyOrgType(companyBaseBean.getCompanyOrgType());
		companyStrengthBean.setOrgApprovedInstitution(companyBaseBean.getOrgApprovedInstitution());
		companyStrengthBean.setBusinessScope(companyBaseBean.getBusinessScope());
		companyStrengthBean.setRegTime(this._formatDate(companyBaseBean.getRegTime()));
		companyStrengthBean.setAnnualSales(companyBaseBean.getAnnualSales());
		companyStrengthBean.setRegCapital(companyBaseBean.getRegCapital());
		companyStrengthBean.setRegUnit(companyBaseBean.getRegUnit());
		companyStrengthBean.setFinanceAmount(financeAmount);
		companyStrengthBean.setFinanceRound(financeRound);
		companyStrengthBean.setExternalQuantity(3);
		companyStrengthBean.setIndexBaidu(companyBaseBean.getIndexBaidu());
		companyStrengthBean.setIndexWechat(companyBaseBean.getIndexWechat());
		return ResponseObject.successObject(companyStrengthBean);
	}

	/**
	 * @desc 根据企业UID判断企业是否存在
	 * @param companyUid
	 * @return
	 */
	@Override
	public int isExist(String companyUid) {
		return tbCompanyInfoMapper.isExist(companyUid);
	}

	/**
	 * @desc 我的企业信息
	 * @return
	 */
	@Override
	public ResponseObject companyMe() {
		UserInfo userInfo = LoginAuth.getUserInfo(); // 用户信息

		// ES企业信息
		CompanyBaseBean companyBaseBean = null;
		try {
			RequestCompanyInfoBean requestBean = new RequestCompanyInfoBean();
			requestBean.setUid(userInfo.getCompanyUid());
			String[] attr = { "full_name", "address", "industry", "introduction", "website", "phone", "address",
					"short_name", "logo_url", "business_scope" };
			companyBaseBean = searchCompanyService.queryCompanyInfo(requestBean, attr);
		} catch (Exception e) {
			companyBaseBean = new CompanyBaseBean();
		}

		CompanyBean companyBean = new CompanyBean();
		companyBean.setUid(companyBaseBean.getUid());
		companyBean.setFullName(companyBaseBean.getFullName());
		companyBean.setShortName(companyBaseBean.getShortName());
		companyBean.setLogoUrl(companyBaseBean.getLogoUrl());
		return ResponseObject.successObject(companyBean);
	}

	/**
	 * @desc 比较两个日期时间大小
	 * @param date1
	 * @param date2
	 * @return
	 */
	private boolean _compareDate(String date1, String date2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(date1);
			Date dt2 = df.parse(date2);
			if (dt1.getTime() > dt2.getTime()) {
				return true;
			}
		} catch (Exception exception) {
		}
		return false;
	}

	/**
	 * @desc 格式化日期时间
	 * @param date
	 * @return
	 */
	private String _formatDate(String date) {
		if (StringUtils.isNullOrEmpty(date)) {
			return "";
		}
		// 处理包含"/"的时间
		if (date.indexOf("-") != -1) {
			return date;
		}
		// 处理数字为10的时间
		if (date.length() == 10) {
			date += "000";
		}
		return DateUtil.msecondTimeToString(Long.valueOf(date), "yyyy-MM-dd");
	}

}
